<?php
defined('_XR_EXEC') or die();
/**
 * test module
 */
class order_model extends model
{ 
	public function __construct() {
		parent::__construct();
	}
	/* 订单日志 */
  public function logs($order_id,$logs,$user_id=0){
		$db = factory::getDBO();
		return $db->insert('order_log',array(
			'order_id'=>$order_id,
			'logs'=>$logs,
			'created'=>'now()',
			'created_user_id'=>$user_id
		));
	}
	
	
	
	/* 当前的时间是否在套餐可配送时间段内 */
	public function isInCombosSendArea($combos,$rec_date){
		$datearea = $this->combosSendArea($combos);
		$bdate = $datearea['bdate'];
		$edate = $datearea['edate'];
		if(dates::dateDiff('d',$bdate,$rec_date)<0){
			return false;
		}
		if(dates::dateDiff('d',$rec_date,$edate)<0){
			return false;
		}
		return true;
	}
	/* 
	$combos = Array
(
    [0] => 24
    [1] => 20
)

	 */
	/* 计算套餐产品的开始时间和结束时间 */
	public function combosSendArea($combos,$san=false){
		if(!is_array($combos) || count($combos)<=0){
			return false;
		}
		$db = factory::getDBO();
		$rs = $db->loadassoclist('select sendbdate,sendedate from t_combo where id in ('.implode(',',$combos).')');
		if(!$rs){
			return false;
		}
		$bdate = date('Y-m-d',dates::addDay(time(),3) );
		$edate = '';
		//先计算开始日期，选出最迟的开始时间
		foreach($rs as $v){
			//比较，最迟的开始时间
			if( dates::dateDiff('d',$bdate,$v['sendbdate']) > 0 ){
				$bdate = $v['sendbdate'];
			} 
			//比较，最早的结束时间 
			if($edate == ''){
				$edate = $v['sendedate'];
			}else{
				if( dates::dateDiff('d',$v['sendedate'],$edate) > 0 ){
					$edate = $v['sendedate'];
				}
			} 
		}
		if(dates::dateDiff('d',$bdate,$edate)<0){
			return false;
		}
		if($san === true){
			$max_show_sltdate = 20;//最大可供用户选择的日期数目（由于管理员配置失误的原因，导致可选择几个月或者几年，所以要有一个最大数）
			# 打散显示，有几天可以选择
			$alw_rec_date = dates::dateDiff('d',$bdate,$edate);
			if($alw_rec_date > $max_show_sltdate){
				$alw_rec_date = $max_show_sltdate;
			}
			$rec_date = array( $bdate );
			for($ii=1; $ii<=$alw_rec_date; $ii++){
				$rec_date[] = date('Y-m-d',dates::addDay(strtotime($bdate),$ii) );
			}
			return $rec_date;
		}else{
			return array('bdate'=>$bdate,'edate'=>$edate);
		}
	}
	
	
	/* 
	$goods=  Array
        (
            [combo_id] => 8
            [nums] => 1
            [cart_item] => Array
                (
                    [0] => Array
                        (
                            [vege_id] => 122
                            [vege_num] => 1
                        )

                    [1] => Array
                        (
                            [vege_id] => 126
                            [vege_num] => 1
                        )

                    [2] => Array
                        (
                            [vege_id] => 125
                            [vege_num] => 1
                        ) 

                )

        )

    [1] => Array
        (
            [combo_id] => 5
            [nums] => 1
            [cart_item] => Array
                (
                )

        )

	 */
	public function submitOrder($user_id,$goods,$created_user_id,$finish_cart,$rec_date,$sendtime='1'){
			$m_trans = factory::module('trans');
			$m_point = factory::module('point');
			$db = factory::getDBO();
			$db->begin();
			
			$rs_user = $db->loadassoc('select * from t_user where id="'.$user_id.'" ');
			if(!$rs_user){
				return $this->setError('会员信息不存在');
			}
			if(count($goods) <= 0){
				return $this->setError('订单产品不存在');
			}
			foreach($goods as &$v){
				$tmp_rs_combo = $db->loadassoc('select 
					name as combo_name ,
					type as combo_type ,
					price as combo_price,
					min_num as combo_min_num 
				from t_combo where id="'.$v['combo_id'].'" ');
				$v['combo_name']		= $tmp_rs_combo['combo_name'];
				$v['combo_type'] 		= $tmp_rs_combo['combo_type'];
				$v['combo_price'] 	= $tmp_rs_combo['combo_price'];
				$v['combo_min_num'] = $tmp_rs_combo['combo_min_num'];
				 
				# 组合套餐特殊处理
				if($tmp_rs_combo['combo_type'] == '1'){
					$tmp_price_total = 0;
					foreach($v['cart_item'] as $k=>$val){
						$tmp_vege = $db->loadassoc('select price,name from t_vege where id="'.$val['vege_id'].'" ');
						$v['cart_item'][$k]['vege_price'] = $tmp_vege['price'];
						$v['cart_item'][$k]['vege_name'] = $tmp_vege['name'];
						$tmp_price_total += $tmp_vege['price'] * intval($val['vege_num']);
					}
					$v['price'] = $tmp_price_total;
					$v['price_total'] = $tmp_price_total * $v['nums'];
					$v['combo_item'] = array();
				}else{
					$v['price'] = $tmp_rs_combo['combo_price'];
					$v['price_total'] = $tmp_rs_combo['combo_price'] * $v['nums'];
					$v['combo_item'] = $db->loadassoclist('
						select 
						a.vege_id,
						a.vege_num,
						b.price as vege_price,
						b.name as vege_name
						from t_combo_item a left join t_vege b on a.vege_id=b.id 
						where a.combo_id="'.$v['combo_id'].'"
					');
				}
			}
			# 将价格更新一遍，并且计算总份数以及总金额
			$pricetotal = 0;
			$fenshu = 0;
			foreach($goods as $vv){
				$pricetotal += $vv['price_total'];
				$one_fenshu = 0;
				if($vv['combo_type'] == 0){
					foreach($vv['combo_item'] as $val){
						$one_fenshu += $val['vege_num'];
					}
				}else{
					foreach($vv['cart_item'] as $vals){
						$one_fenshu += $vals['vege_num'];
					}
				}
				$fenshu += $one_fenshu*$vv['nums'];
			}
			
			# 计算运费
			$yunfee = $this->caclyunfee($user_id,$fenshu,$pricetotal);
			
			if($yunfee === false){
				return $this->setError('下单用户暂未设置配送方式');
			}
			
			# 开始搞订单
			$ordercode = date('Ymd').rand(100000,999999);
			
			# 订单配送日期
			
		//	debug::show($rec_date);
			
			
			# 订单主表
			$order_id = $db->insert('order',array(
				'code'=>$ordercode,
				'status'=>'0',
				'price_all'=>$pricetotal,
				'price_deliver'=>$yunfee,
				'price_free'=>0,
				'price_total'=>($pricetotal+$yunfee),
				'point_total'=>0,
				'vege_nums'=>$fenshu,
				'trans_flag'=>0,
				'user_id'=>$user_id,
				'remark'=>'',
				'cancelremark'=>'',
				'created_user_id'=>$created_user_id,
				'created'=>'now()',
				'deliver_id'=>$rs_user['deliver_id'],
				'sendtime'=>$sendtime,
				'rec_date'=>$rec_date
			));
			if(!$order_id){
				return $this->setError('订单提交失败#1');
			} 
			$this->logs($order_id,'提交订单');
			
			 
			# 订单商品
			foreach($goods as $vv){
				$order_goods_id = $db->insert('order_goods',array(
					'order_id'=>$order_id,
					'user_id'=>$user_id,
					'combo_id'=>$vv['combo_id'],
					'combo_name'=>$vv['combo_name'],
					'combo_type'=>$vv['combo_type'],
					'combo_min_num'=> $vv['combo_min_num'],
					'price'=>$vv['price'],
					'nums'=> $vv['nums'],
					'price_total'=> $vv['price_total']
				));
				if(!$order_goods_id){
					return $this->setError('订单提交失败#2');
				} 
				#订单商品明细
				if($vv['combo_type'] == '0'){
					//固定套餐
					if(count($vv['combo_item'])>0){
						foreach($vv['combo_item'] as $val){
							$db->insert('order_goods_item',array(
								'order_id'=>$order_id,
								'order_goods_id'=>$order_goods_id,
								'vege_id'=>$val['vege_id'],
								'vege_price'=>$val['vege_price'],
								'vege_num'=>$val['vege_num']
							));
						}
					}
				}else{
					//组合套餐
					if(count($vv['cart_item'])>0){
						foreach($vv['cart_item'] as $val){
							$db->insert('order_goods_item',array(
								'order_id'=>$order_id,
								'order_goods_id'=>$order_goods_id,
								'vege_id'=>$val['vege_id'],
								'vege_price'=>$val['vege_price'],
								'vege_num'=>$val['vege_num']
							));
						}
					}
				}
			}
			
			# 判断是否余额足够扣除,要划账，进行更新订单对应的字段值
			if(!$m_trans->add_byslug('order',$user_id,($pricetotal+$yunfee),'订单消费扣款，订单编号：'.$ordercode,$created_user_id,func::get_client_ip(),true,$order_id)){
			  if($m_trans->getErrorNum()=='20'){
					return $this->setError( '余额不足，订单总金额：￥'.($pricetotal+$yunfee).'，会员当前余额：￥'.$m_trans->getbalance($user_id)  );
				}
				return $this->setError( $m_trans->getError() );
			}
			#更新订单支付状态
			$db->update('order',array(
				'id'=>$order_id,
				'status'=>'1',
				'trans_flag'=>'1',
				'trans_total'=>($pricetotal+$yunfee),
				'trans_balance'=>$m_trans->getbalance($user_id)
			));
			
			
			# 计算积分
			$jifen = 0;
			# 订单商品
			foreach($goods as $vv){
				$thecombo = $db->loadassoc('select * from t_combo where id="'.$vv['combo_id'].'" ');
				if($thecombo['point_flag'] == '1'){
					if($thecombo['point_type'] == '0'){
						//按金额
						if($thecombo['point_every'] <= 0){
							$jifen += 0;
						}else{
							$jifen += floor($vv['price_total']/$thecombo['point_every']);
						}
					}else{
						//按固定积分
						$jifen += $vv['nums'] * $thecombo['point_fix'];
					}
				}
			}
			if($jifen > 0){
				if(!$m_point->add_byslug('order',$user_id,$jifen,'订单消费赠送，订单编号：'.$ordercode,$created_user_id,func::get_client_ip(),true,$order_id)){
					return $this->setError( $m_trans->getError() );
				}
				# 更新订单表
				$db->update('order',array(
					'id'=>$order_id,
					'point_total'=>$jifen,
					'point_balance'=>$m_point->getbalance($user_id)
				));
			}
			
			
			
			# 清空购物车
			if($finish_cart === true){
				$db->query('update t_cart set deleted=1 where user_id="'.$user_id.'"');
			}
			$db->commit();
			return array(
				'id'=>$order_id,
				'code'=>$ordercode,
				'price_all'=>$pricetotal,
				'price_deliver'=>$yunfee,
				'price_total'=>($pricetotal+$yunfee),
				'point_total'=>$jifen,
				'point_balance'=>$m_point->getbalance($user_id),
				'trans_total'=>($pricetotal+$yunfee),
				'trans_balance'=>$m_trans->getbalance($user_id)
			);
	}
	/* 计算运费 */
	public function caclyunfee($user_id,$fenshu,$pricetotal){
		$db = factory::getDBO();
		$rs_deliver = $db->loadassoc('select a.* from t_deliver a left join t_user b on a.id=b.deliver_id where b.id="'.$user_id.'" ');
		if(!$rs_deliver){
			return false;
		}
		if($rs_deliver['wfree_flag'] == '1'){
			if($fenshu >= $rs_deliver['wfree_val']){
				return 0;
			}
		}
		if($rs_deliver['mfree_flag'] == '1'){
			if($pricetotal >= $rs_deliver['mfree_val']){
				return 0;
			}
		}
		# 基础价格
		$fee = $rs_deliver['price_first'];
		$fenshu = $fenshu-$rs_deliver['weight_first'];
		if($fenshu <= 0){
			return $fee;
		}
		if($rs_deliver['weight_xu'] <= 0){
			return $fee;
		}
		$fee += ceil($fenshu/$rs_deliver['weight_xu']) * $rs_deliver['price_xu'];
		return $fee;
	}

	/* 取消订单-用户取消 */
	public function cancelByUser($order_id,$user_id){
		$db = factory::getDBO();
		$db->begin();
		
		$rs = $db->loadassoc('select * from t_order where id="'.$order_id.'" and user_id="'.$user_id.'" ');
		if(!$rs){
			return $this->setError('订单不存在');
		}
		if($rs['status']!='1'){
			return $this->setError('只能取消【等待审核】状态下的订单');
		}
		# 更新订单状态
		$db->update('order',array(
			'id'=>$rs['id'],
			'canceldate'=>'now()',
			'status'=>'-1'
		));
		# 记录订单日志
		$this->logs($rs['id'],'用户取消订单');
		
		# 是否有过账，需要返还金额
		if($rs['trans_flag'] == '1'){
			$m_trans = factory::module('trans');
			//debug::show('ordercancel',$user_id,$rs['price_total'],'订单撤销返款，订单编号：'.$rs['code'],'1','',true,$order_id);
			if(!$m_trans->add_byslug('ordercancel',$user_id,$rs['price_total'],'订单撤销返还，订单编号：'.$rs['code'],'1','',true,$order_id)){
				return $this->setError('取消订单异常');
			}
		}
		# 退换积分
		if($rs['point_total'] > 0){
			$m_point = factory::module('point');
			// debug::show('ordercancel',$user_id,$rs['point_total'],'订单撤销扣除，订单编号：'.$rs['code'],'1','',true,$order_id);
			if(!$m_point->add_byslug('ordercancel',$user_id,$rs['point_total'],'订单撤销扣除，订单编号：'.$rs['code'],'1','',true,$order_id)){
				return $this->setError('取消订单异常');
			}
		}
		
		
		$db->commit();
		return true;
	}
	/* 取消订单-系统取消 */
	public function cancelBySys($order_id){
		$db = factory::getDBO();
		$db->begin();
		
		$rs = $db->loadassoc('select * from t_order where id="'.$order_id.'"  ');
		if(!$rs){
			return $this->setError('订单不存在');
		}
		if($rs['status']=='-2' || $rs['status']=='-1'){
			return $this->setError('订单状态已经是取消状态');
		}
		# 更新订单状态
		$db->update('order',array(
			'id'=>$rs['id'],
			'canceldate'=>'now()',
			'status'=>'-2'
		));
		# 记录订单日志
		$this->logs($rs['id'],'系统取消订单');
		
		# 是否有过账，需要返还金额
		if($rs['trans_flag'] == '1'){
			$m_trans = factory::module('trans');
			if(!$m_trans->add_byslug('ordercancel',$rs['user_id'],$rs['price_total'],'订单撤销返还，订单编号：'.$rs['code'],'1','',true,$order_id)){
				return $this->setError('取消订单异常');
			}
		}
		# 退换积分
		if($rs['point_total'] > 0){
			$m_point = factory::module('point');
		 
			if(!$m_point->add_byslug('ordercancel',$rs['user_id'],$rs['point_total'],'订单撤销扣除，订单编号：'.$rs['code'],'1','',true,$order_id)){
				return $this->setError('取消订单异常');
			}
		}
		
		
		$db->commit();
		return true;
	}
	
	
	 
}

?>